package com.company.zonghelizi.xiancheng;

/**
 *      线程应用例子
 * 生成一个答案 随机 1-20
 * 两个线程分别去猜答案，随机猜
 * 其中一个500毫秒猜一次。另一个每1秒猜一次
 * 谁猜中了就结束
 * 统计一共花了多少时间
 */

public class Test {
    // 实现1
    public static void main(String[] args) throws InterruptedException {
        long startTime=System.currentTimeMillis();
        int anser = (int)(Math.random()*20)+1;
        // 两个线程其中一个执行完都结束的办法：
        // 设置一个总的变量，两个线程都访问同一个变量，在一个线程改变时第二个线程再去访问该参数时就会是访问后的值
        final boolean[] gameover = new boolean[1];
        Thread th1 = new Thread(()->{
            while (!gameover[0]){
                if(anser==(int)(Math.random()*20)+1){
                    System.out.println(Thread.currentThread()+"猜中了");
                    gameover[0] = true;
                    break;
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread th2 = new Thread(()->{
            while (!gameover[0]){
                if(anser==(int)(Math.random()*20)+1){
                    System.out.println(Thread.currentThread()+"猜中了");
                    gameover[0] = true;
                    break;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        th1.start();
        th2.start();

        th1.join();
        th2.join();

        long endTime=System.currentTimeMillis();
        System.out.println(endTime-startTime);
    }
}


// 实现2
class GuessThread extends Thread{
    private int time;
    private int answer;

    private static boolean gameover = false;

    public GuessThread(int time,int answer){
        this.time = time;
        this.answer = answer;
    }

    @Override
    public void run() {
        while (!gameover){
            try {
                Thread.sleep(time);
                int num = (int)(Math.random()*20+1);
                System.out.println(Thread.currentThread()+"猜的是"+num);
                if(num==answer){
                    System.out.println(this+"猜中了");
                    gameover = true;
                    break;
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Tests{
    public static void main(String[] args) throws InterruptedException {
        long startTime=System.currentTimeMillis();
        int answer = (int)(Math.random()*20)+1;
        System.out.println("答案是"+answer);
        GuessThread th1 = new GuessThread(500,answer);
        GuessThread th2 = new GuessThread(1000,answer);
        th1.start();
        th2.start();
        th1.join();
        th2.join();
        long endTime=System.currentTimeMillis();
        System.out.println(endTime-startTime);

    }
}
